// 后台-玩家框的配置
const adminScreen = UiScreen.getAllScreen().find(
    (e) => e.name === 'adminScreen'
);
const S_userBoxContent = adminScreen?.findChildByName<UiBox>('UserContent'); // 滑动框
const S_Content = S_userBoxContent?.findChildByName<UiScrollBox>('Content');
const S_userBox = S_Content?.findChildByName<UiBox>('UserBox'); // Box
if (S_userBox) {
    S_userBox.visible = false;
    S_userBox.position.offset.y -= S_userBox.size.offset.y + 10;
}
interface playerData {
    userId: string;
    name: string;
    avatar: string;
}
class UserBox {
    box: UiBox | undefined;
    players: playerData[] = [];
    id: number = -1;
    title: string = '';
    handle: (
        UserId: string,
        Name: string,
        Avatar: string,
        target: UiNode
    ) => void = () => {};
    constructor(
        inScreen: string,
        id: number,
        title: string,
        coord: Coord2,
        anchor: Vec2,
        players: playerData[],
        handle: (
            UserId: string,
            Name: string,
            Avatar: string,
            target: UiNode
        ) => void
    ) {
        if (!S_userBoxContent) {
            return;
        }
        this.id = id;
        // 克隆元素
        this.box = S_userBoxContent.clone();
        const titleBox = this.box.findChildByName<UiText>('Title');
        if (titleBox) {
            titleBox.textContent = title;
        }
        // 配置玩家数据
        this.players = players;
        // 设置UI元素的屏幕位置
        const parent = UiScreen.getAllScreen().find((e) => e.name === inScreen);
        this.box.parent = parent;
        // 更新位置
        if (this.box && this.box.position) {
            this.box.position.offset.copy(coord.offset);
            this.box.position.scale.copy(coord.scale);
            this.box.anchor.copy(anchor);
        }

        // 声明Click
        this.handle = handle;

        // 加载玩家列表
        // console.log('尝试加载。');
        this.showPlayer();
    }

    /**加载列表 */
    showPlayer() {
        try {
            // console.log('加载1');
            if (!this.box) {
                return;
            }
            const Content = this.box.findChildByName<UiScrollBox>('Content');
            if (!Content) {
                return;
            }
            const userBox = Content.findChildByName<UiBox>('UserBox');
            if (!userBox) {
                return;
            }
            for (const e of this.players) {
                const cloneBox = userBox?.clone();
                // console.log('加载2', "" + cloneBox);
                if (cloneBox) {
                    cloneBox.visible = true;
                    cloneBox.name = 'cloneUserBox';
                    // console.log('加载3');
                    cloneBox.position.offset.y += cloneBox?.size.offset.y + 10;
                    userBox.position.offset.y += userBox?.size.offset.y + 10;
                    // console.warn(cloneBox.position.offset.y);
                    // cloneBox.events.on("pointerdown", this.click);

                    const Name = cloneBox?.findChildByName<UiText>('Name');
                    const UserId = cloneBox?.findChildByName<UiText>('UserId');
                    const Avatar = cloneBox?.findChildByName<UiImage>('Avatar');

                    if (Name && UserId && Avatar) {
                        Name.textContent = e.name;
                        UserId.textContent = e.userId;
                        Avatar.image = e.avatar;
                        cloneBox.events.add('pointerup', () => {
                            this.click(
                                UserId.textContent,
                                Name.textContent,
                                Avatar.image,
                                cloneBox
                            );
                        });
                        // console.log('加载4');
                    }
                }
            }
        } catch (e) {
            console.error(e);
        }
    }

    /**更新Players数据，UI也会同时更新。 */
    updatePlayer(players: playerData[]) {
        // console.log('获取数据');
        try {
            this.players = players;
            if (!this.box) {
                return;
            }
            const Content = this.box.findChildByName<UiScrollBox>('Content');
            if (!Content) {
                return;
            }
            const inputBox = this.box.findChildByName<UiText>('search');
            if (!inputBox) {
                return;
            }
            const result = inputBox.textContent;
            if (result && result.length > 0) {
                this.players = this.players.filter((e) => {
                    return e.userId.includes(result) || e.name.includes(result);
                });
            }
            // console.log('获取数据2');
            // 删除
            for (const e of Content?.children) {
                if (e.name === 'cloneUserBox') {
                    const UserId = e?.findChildByName<UiText>('UserId')
                        ?.textContent as string;
                    // console.log(players.map((a) => a.userId), UserId, players.map((a) => a.userId).includes(UserId));
                    /**复制算法以子系第一个 */
                    if (!this.players.map((a) => a.userId).includes(UserId)) {
                        e.parent = undefined;
                    }
                }
            }
            // console.log('获取数据3');
            const allUserIds = Content?.children.map((e) => {
                const UserId = e?.findChildByName<UiText>('UserId');
                return UserId?.textContent;
            });
            // console.log('获取数据4');

            /**获取可添加最底部的地方 */
            const userBox = Content?.findChildByName<UiBox>('UserBox');
            // console.log(userBox + '');
            if (!userBox) {
                return;
            }

            let startY: number = -(userBox?.size.offset.y + 10);
            // console.log(startY);
            if (Content?.children.find((e) => e.name === 'cloneUserBox')) {
                startY = Content?.children
                    .filter((e) => e.name === 'cloneUserBox')
                    .map((e) => {
                        const a = e as UiRenderable;
                        return a.position.offset.y;
                    })
                    .sort((a, b) => {
                        return b - a;
                    })[0] as number;
                // startY -= userBox.size.offset.y + 10;
            }
            // console.log('获取数据5', Content.children.map(e => e.name));
            if (userBox) {
                // console.log('获取数据5');
                userBox.position.offset.y = startY;
                // console.warn(userBox.position.offset.y);
                userBox.parent = Content;
                for (const e of this.players) {
                    if (!allUserIds?.includes(e.userId)) {
                        const cloneBox = userBox?.clone();
                        if (cloneBox) {
                            cloneBox.name = 'cloneUserBox';
                            cloneBox.visible = true;

                            // cloneBox.position.offset.y +=
                            //     cloneBox?.size.offset.y + 10;
                            // userBox.position.offset.y +=
                            //     userBox?.size.offset.y + 10;
                            // console.warn(userBox.position.offset.y, cloneBox.position.offset.y);
                            const Name =
                                cloneBox?.findChildByName<UiText>('Name');
                            const UserId =
                                cloneBox?.findChildByName<UiText>('UserId');
                            const Avatar =
                                cloneBox?.findChildByName<UiImage>('Avatar');
                            if (Name && UserId && Avatar) {
                                Name.textContent = e.name;
                                UserId.textContent = e.userId;
                                Avatar.image = e.avatar;
                                cloneBox.events.add('pointerup', () => {
                                    this.click(
                                        UserId.textContent,
                                        Name.textContent,
                                        Avatar.image,
                                        cloneBox
                                    );
                                });
                            }
                        }
                    }
                }
            }

            // let index = 0;
            // // 重新排序，防止删除数据后有空行
            // for (const e of Content?.children) {
            //     const a = e as UiRenderable;
            //     a.position.offset.y = index * (a.size.offset.y + 10);
            //     index++;
            // }
            this.updateSort();
        } catch (e) {
            console.error(e);
        }
    }
    /**更新children子类排序 */
    updateSort() {
        // 主要以UID排序
        if (!this.box) {
            return;
        }

        let index = 0;

        const Content = this.box.findChildByName<UiScrollBox>('Content');
        if (!Content) {
            return;
        }

        // const userIdSort = Content?.children.map((e) => {
        //     const a = e.findChildByName<UiText>('UserId');
        //     return a?.textContent;
        // }).sort((a, b) => (a as string)?.length - (b as string).length);

        // 重新排序，防止删除数据后有空行
        for (const e of Content?.children) {
            const a = e as UiRenderable;
            a.position.offset.y = index * (a.size.offset.y + 10);
            index++;
        }
    }

    /** 销毁 */
    destroy() {
        if (!this.box) {
            return;
        }
        this.box.parent = undefined;
    }

    /**点击事件 */
    click(UserId: string, Name: string, Avatar: string, target: UiNode) {
        this.handle(UserId, Name, Avatar, target);
    }

    /** */
}

export { UserBox, playerData };
